package com.qlm.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.qlm.entity.Yjjf;
import com.qlm.entity.Yscore;
import com.qlm.service.IYyyScoreService;
import com.qlm.tools.Common;
import com.qlm.view.ResultMessage;

public class YyyScoreServiceImpl implements IYyyScoreService {
	private static final Logger logger = LoggerFactory.getLogger(YyyScoreServiceImpl.class);

	@Override
	public List<Yscore> getScoreConfig() {
		return Yscore.dao.find("select score_,rate_ from t_yyy_scoreconfig");
	}

	@Override
	@Before(Tx.class)
	public ResultMessage saveScoreConfig(Integer[] score_, String[] rate_) {
		if(!Common.isNullOrEmpty(score_) && !Common.isNullOrEmpty(rate_) &&
				score_.length == rate_.length && rate_.length>0){
			Db.update("delete from t_yyy_scoreconfig");
			int len = rate_.length;
			List<Yscore> list = new ArrayList<Yscore>();
			for (int i = 0; i < len; i++) {
				Yscore s = new Yscore();
				s.set("score_", score_[i]).set("rate_", rate_[i]);
				list.add(s);
			}
			String sql = "insert into t_yyy_scoreconfig(score_,rate_) values(?,?)";
			String columns = "score_,rate_";
			Db.batch(sql, columns, list, list.size());
			callCache("cache/updateYYY");
			return new ResultMessage(1,"保存积分配置成功",null);
		}
		return new ResultMessage(0,"网络连接错误",null);
	}

	@Override
	public ResultMessage saveYjjf(Integer score) {
		if(!Common.isNullOrEmpty(score)){
			Yjjf yjjf = Yjjf.dao.findFirst("select * from t_yyy_yjjf");
			if(Common.isNullOrEmpty(yjjf)){
				new Yjjf().set("score_", score).save();
			}else{
				yjjf.set("score_", score).update();
			}
			callCache("cache/updateYYY");
			return new ResultMessage(1,"摇奖积分配置成功",null);
		}
		return new ResultMessage(0,"网络连接错误",null);
	}

	public Yjjf getYjjf(){
		return Yjjf.dao.findFirst("select * from t_yyy_yjjf");
	}

	/**
	 * 发送请求给cache更新
	 * @param type
	 */
	public static void callCache(String type){
			new Thread(new Runnable() {
				public void run() {
					String cacheUrl = PropKit.get("cacheUrl");
					String[] urlArr = cacheUrl.split(",");
					try{						
						for(int i=0;i<urlArr.length;i++){
							if(Common.isEmptyString(urlArr[i])){
								HttpKit.get(urlArr[i] + type);
								logger.info(urlArr[i]+type+"请求发送成功");
							}							
						}
					}catch(Exception e){
						logger.error(e.getMessage(), e);
					}							
				}
			}).start();
	}
}
